package middleware

import (
	"app/internal/model"
	"app/pkg/config"
	"app/pkg/jwt"
	"strings"
	"time"

	"github.com/gin-gonic/gin"
)

// JwtMiddleware jwt中间件
func InitUserinfoMiddleware() gin.HandlerFunc {
	return func(c *gin.Context) {
		//从请求头中获取token
		tokenStr := c.Request.Header.Get("Authorization")
		if tokenStr != "" {
			//token格式错误
			tokenSlice := strings.SplitN(tokenStr, " ", 2)
			if len(tokenSlice) != 2 || tokenSlice[0] != "Bearer" {
				c.Next()
				return
			}
			//验证token
			tokenStruck, ok := jwt.CheckToken(tokenSlice[1], config.Config.App.JwtSignKey)
			if !ok {
				c.Next()
				return
			}
			//token超时
			if time.Now().Unix() > tokenStruck.ExpiresAt {
				c.Next()
				return
			}
			var user model.UserModel
			user, _ = model.FindOne[model.UserModel](map[string]interface{}{"id": tokenStruck.Uid})
			c.Set("uid", tokenStruck.Uid)     //用户ID
			c.Set("username", user.Username)  //用户名
			c.Set("phone", user.Phone)        //用户名
			c.Set("pass_salt", user.PassSalt) //密码salt
		}
		c.Next()
	}
}
